import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {  
    cartItems: [  
      { id: 1, name: '手机', price: 1000, quantity: 0 },  
      { id: 2, name: '电脑', price: 2000, quantity: 0 },  
      { id: 3, name: '键盘', price: 200, quantity: 0 }  
    ]  
  },  
  mutations: {  
    addToCart(state, item) {  
      // 检查是否已存在  
      let cartItem = state.cartItems.find(i => i.id === item.id);  
      if (cartItem) {  
        cartItem.quantity++;  
      } else {  
        state.cartItems.push({ ...item, quantity: 1 });  
      }  
    },  
    removeFromCart(state, itemId) {  
      let cartItem = state.cartItems.find(i => i.id === itemId);  
      if (cartItem && cartItem.quantity > 1) {  
        cartItem.quantity--;  
      } else if (cartItem) {  
        state.cartItems = state.cartItems.filter(i => i.id !== itemId);  
      }  
    },  
    // 其他mutations...  
  },  
  getters: {  
    cartItems: state => state.cartItems,  
    totalPrice: state => {  
      return state.cartItems.reduce((total, item) => total + item.price * item.quantity, 0);  
    }  
  }  
})
